package com.example.menu;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class GameOver extends Activity {
	File localHighScoresFile;
	String[] tokens;
	int result;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_game_over);

		Bundle b = getIntent().getExtras();
		result = (int) b.getDouble("key");

		TextView scoreView = (TextView) findViewById(R.id.gameOverScore);
		scoreView.setText("You Scored: " + String.format("%d", result));

		/*
		 * Bundle bundle = getIntent().getExtras(); String message =
		 * bundle.getString("message");
		 * 
		 * TextView scoreView = (TextView) findViewById(R.id.gameOverScore);
		 * scoreView.setText("You Scored: " +message);
		 */
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.game_over, menu);
		return true;
	}

	public void endGameOver(View view) {
		this.finish();

	}

	/*
	 * public void goToMenu(){ // Create a new game activity Intent intent = new
	 * Intent(this, MainActivity.class); // start the game activity
	 * startActivity(intent); // End the current activity endGameOver(); }
	 */

	public void startGame(View view) {
		// Create a new game activity
		Intent intent = new Intent(this, Game.class);
		// start the game activity
		startActivity(intent);
		// Close the gameOver activity
		endGameOver(view);
	}

	public void saveScore(View view) {
		EditText mEdit;
		mEdit = (EditText) findViewById (R.id.editText1);
		
		openLocalHighScoresFile();
		getHighScores();
		
		String buffer = mEdit.getText().toString();
		String delims = "\n";
		String [] names = buffer.split(delims);
		checkForHighScore(names[0], result);
		writeToFile();

		// finish the GameOver Activity when all the score stuff is done.
		endGameOver(view);
	}

	public void openLocalHighScoresFile() {
		try {
			if (localHighScoresFile == null) {
				String theFile = "localHighScores";
				File direc = new File(Environment.getExternalStorageDirectory()
						+ "/squared/");
				if (direc.mkdir() || direc.isDirectory()) {

					localHighScoresFile = new File(
							Environment.getExternalStorageDirectory()
									+ "/squared/" + theFile + ".txt");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void getHighScores() {
		BufferedReader localHighScoresBufferedReader;
		try {
			localHighScoresBufferedReader = new BufferedReader(new FileReader(
					localHighScoresFile));

			String line = localHighScoresBufferedReader.readLine();
			String delims = ";";
			tokens = line.split(delims);
		} catch (Exception e) {

		}
	}

	// This will be used for loading high scores
	// We can also save times, and full games (so we can do replays perhaps)
	public void writeToFile() {
		File file = null;
		FileWriter fw = null;
		BufferedWriter bw = null;
		PrintWriter pw = null;
		try {
			if (file == null) {
				String theFile = "localHighScores";
				// String theFile = "test";
				File direc = new File(Environment.getExternalStorageDirectory()
						+ "/squared/");
				if (direc.mkdir() || direc.isDirectory()) {
					file = new File(Environment.getExternalStorageDirectory()
							+ "/squared/" + theFile + ".txt");
					fw = new FileWriter(file.getAbsoluteFile());
					bw = new BufferedWriter(fw);
					pw = new PrintWriter(bw);
				}
			}
			String content = "";
			for (int i = 0; i < 20; i++) {
				content += tokens[i] + ";";
			}

			pw.append(content);
			pw.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// name;score;name;score;name;score;
	public int checkForHighScore(String name, double inputScore) {
		int score = (int)inputScore; 
		if (Double.parseDouble(tokens[19]) >= score) return 0;

		// Copy the high scores array into a temp array
		String[] temp = new String[20];
		for (int i=0; i<20; i++) temp[i] = tokens[i];

		// Set the high scores to nothing
		for (int i=0; i<20; i++) tokens[i] = "";
		
		// Start the temp counter at 1 because the odd indices represent the scores
		int temp_counter = 1;
		
		// Start the tokens counter at zero because we start writing in at zero
		int tokens_counter = 0;

		// Go until 20 slots in the array are filled (10 scores)
		while (tokens_counter < 20) {
			if (Double.parseDouble(temp[temp_counter]) < score) {
				tokens[tokens_counter++] = name;
				tokens[tokens_counter++] = score + "";
				score = -1;
			} 
			else {
				tokens[tokens_counter] = temp[temp_counter-1];
				tokens_counter = tokens_counter + 1;
				tokens[tokens_counter] = temp[temp_counter];
				tokens_counter = tokens_counter + 1;
				temp_counter = temp_counter + 2;
			}
		}
		
		return 1;

	}
}
